package cn.shop.admin.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.shop.admin.entity.Feedback;
import cn.shop.admin.req.FeedbackQueryReq;
import cn.shop.admin.service.FeedbackService;
import cn.shop.admin.service.FrontUserService;
import cn.shop.thiredparty.config.OSSConfig;
import cn.shop.transcation.frontUserModule.FrontUser;
import cn.shop.utils.ApiResult;
import cn.shop.utils.PageUtil;
import cn.shop.utils.Putif;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 意见反馈接口
 *
 * @author : 李一涵
 * @date : Created in 2022/10/19 9:33
 * @description :
 */
@RestController
@RequestMapping("/api/v1/feedback")
public class FeedbackController {

    @Resource
    private FeedbackService feedbackService;
    @Resource
    private FrontUserService frontUserService;
    @Resource
    private OSSConfig config;

    private final Predicate<Object> isNotNull = ObjectUtil::isNotNull;

    /**
     * 查看意见反馈列表
     *
     * @param req 筛选条件
     * @return 返回结果
     */
    @GetMapping("")
    public ApiResult<Map<String, Object>> list(FeedbackQueryReq req) {
        Page<Feedback> page = Page.of(req.getCurrent(), req.getSize());
        Map<Long, FrontUser> map = new HashMap<>();
        LambdaQueryChainWrapper<Feedback> query = feedbackService.lambdaQuery()
                .apply(isNotNull.test(req.getStartTime()),
                        req.gtTime("create_time"), req.getStartTime())
                .apply(isNotNull.test(req.getEndTime()),
                        req.ltTime("create_time"), req.getEndTime())
                .eq(isNotNull.test(req.getStatus()), Feedback::getStatus, req.getStatus())
                .eq(isNotNull.test(req.getCategory()), Feedback::getCategory, req.getCategory())
                .orderByDesc(Feedback::getCreateTime);
        if (StrUtil.isNotBlank(req.getMobile())) {
            List<FrontUser> frontUsers = frontUserService.lambdaQuery().eq(FrontUser::getPhone, req.getMobile()).list();
            if (frontUsers.isEmpty()) {
                return ApiResult.success(PageUtil.formatPage(page, f -> format(f, Collections.emptyMap())));
            }
            query.in(Feedback::getUserId, frontUsers.stream().map(FrontUser::getId).collect(Collectors.toList()));
        }
        page = query.page(page);
        List<Long> ids = page.getRecords().stream().map(Feedback::getUserId).collect(Collectors.toList());
        if (!ids.isEmpty()) {
            List<FrontUser> users = frontUserService.lambdaQuery().in(FrontUser::getId, ids).list();
            map = users.stream().collect(Collectors.toMap(FrontUser::getId, u -> u));
        }
        Map<Long, FrontUser> finalMap = map;
        return ApiResult.success(PageUtil.formatPage(page, f -> format(f, finalMap)));
    }

    /**
     * 获取意见反馈详情
     *
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public ApiResult<Map<String, Object>> info(@PathVariable long id) {
        Feedback feedback = feedbackService.getById(id);
        if (feedback == null) {
            return ApiResult.fail("意见反馈不存在", null);
        }
        FrontUser user = frontUserService.getById(feedback.getUserId());
        if (StrUtil.isNotBlank(feedback.getImg())) {
            feedback.setImg(config.getPrefix() + "/" + feedback.getImg());
        }
        return ApiResult.success(format(feedback, user));
    }

    /**
     * 解决意见反馈
     *
     * @param id 编号
     * @return 返回结果
     */
    @PutMapping("/{id}")
    public ApiResult<Map<String, Object>> changeStatus(@PathVariable long id) {
        Feedback feedback = feedbackService.getById(id);
        if (feedback == null) {
            return ApiResult.fail("意见反馈不存在", null);
        }
        feedback.setStatus(1);
        return ApiResult.result(feedbackService.updateById(feedback));
    }

    private Map<String, Object> format(Feedback feedback, Map<Long, FrontUser> userMap) {
        FrontUser user = userMap.get(feedback.getUserId());
        return Putif.start()
                .anyway("id", feedback.getId())
                .anyway("name", user != null ? user.getName() : "")
                .anyway("mobile", user != null ? user.getPhone() : "")
                .anyway("category", feedback.getCategory())
                .anyway("content", feedback.getContent())
                .cond(StrUtil.isNotBlank(feedback.getImg()),  m -> m.anyway("img", config.getPrefix() + "/" + feedback.getImg()))
                .anyway("time", feedback.getCreateTime())
                .anyway("status", feedback.getStatus() == 0 ? "未处理" : "已处理")
                .get();
    }

    private Map<String, Object> format(Feedback feedback, FrontUser user) {
        return Putif.start()
                .anyway("id", feedback.getId())
                .anyway("name", user.getName())
                .anyway("mobile", user.getPhone())
                .anyway("category", feedback.getCategory())
                .anyway("content", feedback.getContent())
                .cond(StrUtil.isNotBlank(feedback.getImg()),  m -> m.anyway("img", config.getPrefix() + "/" + feedback.getImg()))
                .anyway("time", feedback.getCreateTime())
                .anyway("status", feedback.getStatus() == 0 ? "未处理" : "已处理")
                .get();
    }

}
